package com.volunteer.util;

import java.security.MessageDigest;
import java.security.SecureRandom;

/**
 * 工具类
 *
 * @author willow
 * @version v.0.1
 * @date 2018年08月1日
 */
public class Util {
    private static final String WORDS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final SecureRandom RANDOM = new SecureRandom();

    /**
     * 密码加密一次MD5加密，然后再执行加密算法获得
     */
    public static String oneEncryption(String string) {
        return convertMD5(MD5(string));
    }

    /**
     * 密码加密两次MD5加密，然后再执行加密算法获得
     */
    public static String twoEncryption(String string) {
        return convertMD5(MD5(MD5(string)));
    }
    /*
     * MD5加码 生成32位md5码
     */
    private static String MD5(String string){
        MessageDigest md5;
        try{
            md5 = MessageDigest.getInstance("MD5");
        }catch (Exception e){
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = string.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /*
     * 加密解密算法 执行一次加密，两次解密
     */
    private static String convertMD5(String string){
        char[] a = string.toCharArray();
        for (int i = 0; i < a.length; i++){
            a[i] = (char) (a[i] ^ '_');
        }
        return new String(a);
    }

    /**
     * 根据长度获取随机字符
     */
    public static String random(int len) {
        StringBuilder sb = new StringBuilder(len);
        int size = WORDS.length();
        for (int i = 0; i < len; i++)
            sb.append(WORDS.charAt(RANDOM.nextInt(size)));
        return sb.toString();
    }
}
